home *** CD-ROM | disk | FTP | other *** search
/ BBS in a Box 3 / BBS in a box - Trilogy III.iso / Files / Prog / B-C / C++ FAQ Reference 1.0 / C++ FAQ Reference 1.0.rsrc / TEXT_1731.txt < prev    next >
Encoding:
Text File  |  1993-06-30  |  2.0 KB  |  57 lines

  1. Consider this container class of that acts like an array of integers:
  2.  
  3.     //this would go into a header file such as 'Vec.h':
  4.     class Vec {
  5.       int  xlen;
  6.       int* xdata;
  7.       int  check(int i);  //return i if i>=0 && i<xlen else throw exception
  8.     public:
  9.       int         len()             const { return xlen;     }
  10.       const int&  operator[](int i) const { xdata[check(i)]; }
  11.             int&  operator[](int i)       { xdata[check(i)]; }
  12.                   Vec(int L=10) : xlen(L), xdata(new int[L]) { /*verify*/ }
  13.                  ~Vec()                   { delete [] xdata; }
  14.     };
  15.  
  16.     //this would be part of a '.C' file such as 'Vec.C':
  17.     int Vec<T>::check(int i)
  18.     {
  19.       if (i < 0 || i >= xlen) throw BoundsViol("Vec", i, xlen);
  20.       return i;
  21.     }
  22.  
  23. Just as with 'swap()' above, repeating the above over and over for Vec of float, char, String, Vec, Vec-of-Vec-of-Vec, etc, will become tedious.  Hence we create a single class template:
  24.  
  25.     //this would go into a header file such as 'Vec.h':
  26.     template<class T>
  27.     class Vec {
  28.       int  xlen;
  29.       T*   xdata;
  30.       int  check(int i);  //return i if i>=0 && i<xlen else throw exception
  31.     public:
  32.       int       len()             const { return xlen;     }
  33.       const T&  operator[](int i) const { xdata[check(i)]; }
  34.             T&  operator[](int i)       { xdata[check(i)]; }
  35.                 Vec(int L=10) : xlen(L), xdata(new T[L]) { /*verify*/ }
  36.                ~Vec()                   { delete [] xdata; }
  37.     };
  38.  
  39.     //this would be part of a '.C' file such as 'Vec.C':
  40.     template<class T>
  41.     int Vec<T>::check(int i)
  42.     {
  43.       if (i < 0 || i >= xlen) throw BoundsViol("Vec", i, xlen);
  44.       return i;
  45.     }
  46.  
  47. Unlike template functions, template classes (instantiations of class templates) need to be explicit about the parameters over which they are instantiating:
  48.  
  49.     main()
  50.     {
  51.       Vec<int>        vi;
  52.       Vec<float>      vf;
  53.       Vec<char*>      vc;
  54.       Vec<String>     vs;
  55.       Vec< Vec<int> > vv;
  56.     }          // ^^^-- note the space; do NOT use Vec<Vec<int>> since the
  57.                //       'maximal munch' rule would grab a single '>>' token